package com.yfbao.horizon.schedule.tk.meter;

import io.netty.util.internal.PlatformDependent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicLong;

@Slf4j
@Component
public class NettyMemoryMetrics {

    private final String filed_name ="DIRECT_MEMORY_COUNTER";

    private final int _1K = 1024;

    private AtomicLong metricCount;

    private ThreadPoolTaskScheduler taskScheduler;

    public NettyMemoryMetrics(){
        taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(1); // 核心线程数
        taskScheduler.setThreadNamePrefix("NettyMemoryMetrics-scheduler-");
        taskScheduler.setAwaitTerminationSeconds(20);
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        taskScheduler.initialize();

        Field field = ReflectionUtils.findField(PlatformDependent.class, filed_name);
        field.setAccessible(true);
        try {
            metricCount = (AtomicLong) field.get(PlatformDependent.class);
        } catch (IllegalAccessException e) {
            log.error("NettyMemoryMetrics init error",e);
            e.printStackTrace();
        }


        taskScheduler.execute(()->{
            try {
                long l = metricCount.get() / _1K;
                log.info("NettyMemoryMetrics size:{}",l);
            }catch (Throwable t){
                log.error("NettyMemoryMetrics sleep error",t);
            }
        });
    }

}
